package com.yys.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yys.common.constant.CartConstant;
import com.yys.common.utils.R;
import com.yys.gulimall.cart.feign.ProductFeignService;
import com.yys.gulimall.cart.interceptor.CartInterceptor;
import com.yys.gulimall.cart.service.CartService;
import com.yys.gulimall.cart.vo.Cart;
import com.yys.gulimall.cart.vo.CartItem;
import com.yys.gulimall.cart.vo.SkuInfoVo;
import com.yys.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author zq
 * @version 1.0
 * @date 2021/3/31 16:32
 */
@Slf4j
@Service("CartService")
public class CartServiceImpl implements CartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        /*
          若保存过数据只需要更新数量即可
          若没有需要新增商品信息
          */
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isBlank(res)) {
            // 购物车无此商品
            //添加新商品到购物车
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 远程调用查询skuInfo
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfo.getPrice());
            },threadPoolExecutor);

            // 远程查询sku的组合信息 使用异步调度
            CompletableFuture<Void> getSkuSaleAttr = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, threadPoolExecutor);

            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttr).get();

            saveCartItemToCart(skuId,cartItem,cartOps);
            return cartItem;

        } else {
            //有商品 更新count
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            // 保存购物车
            saveCartItemToCart(skuId,cartItem,cartOps);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        // 判断登录状态
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if(ObjectUtils.isNotNull(userInfoTo.getUserId())) {
            String userId = CartConstant.CART_PREFIX +  userInfoTo.getUserId();
            String userKey = CartConstant.CART_PREFIX + userInfoTo.getUserkey();
            // 若还有临时购物车的数据还没合并,需要合并
            List<CartItem> tempCartItems = getCartItems(userKey);
            if(ObjectUtils.isNotEmpty(tempCartItems)) {
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                // 清除临时购物车
                this.clearCart(userKey);
            }
            // 获取登录后的购物车数据 这里已经包含了所有购物车数据了
            List<CartItem> cartItems = getCartItems(userId);
            cart.setItems(cartItems);
        } else {
            // 没登录 只获取临时购物车
            String userkey = CartConstant.CART_PREFIX +  userInfoTo.getUserkey();
            List<CartItem> cartItems = getCartItems(userkey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 将购物车存入redis
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 判断是临时购物车还是用户购物车
        String cartKey;
        if(ObjectUtils.isNotNull(userInfoTo.getUserId())) {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserkey();
        }
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(ObjectUtils.isNotEmpty(values)) {
            return values.stream().map(item -> JSON.parseObject((String) item, CartItem.class))
                    .collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        saveCartItemToCart(skuId,cartItem,cartOps);
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(ObjectUtils.isNotNull(userInfoTo.getUserId())) {
            List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserId());
            List<CartItem> collect = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(cartItems)) {
                collect = cartItems.stream().filter(CartItem::getCheck)
                        .peek(item->{
                            // 更新价格
                            BigDecimal price = productFeignService.getPrice(item.getSkuId());
                            item.setPrice(price);
                        })
                        .collect(Collectors.toList());
            }
            return collect;
        }
        return null;
    }

    private void saveCartItemToCart(Long key,CartItem cartItem,BoundHashOperations<String, Object, Object> cartOps) {
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(key.toString(),jsonString);
    }
}
